package com.example.scene;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import org.andengine.engine.camera.Camera;
import org.andengine.engine.handler.timer.ITimerCallback;
import org.andengine.engine.handler.timer.TimerHandler;
import org.andengine.entity.IEntity;
import org.andengine.entity.IEntityFactory;
import org.andengine.entity.modifier.LoopEntityModifier;
import org.andengine.entity.modifier.MoveYModifier;
import org.andengine.entity.modifier.RotationModifier;
import org.andengine.entity.modifier.ScaleModifier;
import org.andengine.entity.modifier.SequenceEntityModifier;
import org.andengine.entity.particle.ParticleSystem;
import org.andengine.entity.particle.emitter.PointParticleEmitter;
import org.andengine.entity.particle.initializer.VelocityParticleInitializer;
import org.andengine.entity.particle.modifier.AlphaParticleModifier;
import org.andengine.entity.particle.modifier.ExpireParticleInitializer;
import org.andengine.entity.particle.modifier.RotationParticleModifier;
import org.andengine.entity.particle.modifier.ScaleParticleModifier;
import org.andengine.entity.primitive.Line;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.menu.MenuScene;
import org.andengine.entity.scene.menu.MenuScene.IOnMenuItemClickListener;
import org.andengine.entity.scene.menu.item.IMenuItem;
import org.andengine.entity.scene.menu.item.SpriteMenuItem;
import org.andengine.entity.scene.menu.item.decorator.ScaleMenuItemDecorator;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.sprite.TiledSprite;
import org.andengine.entity.text.Text;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.util.GLState;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.R.bool;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.Toast;

import com.example.base.BaseScene;
import com.example.fruitpool.Point;
import com.example.input.Score;
import com.example.input.topscore;
import com.example.manager.SceneManager;
import com.example.manager.SceneManager.SceneType;

public class HighScores extends BaseScene implements IOnSceneTouchListener{

	private Text mTitle, mHeaders;
	private Text[] mScoreL = new Text[5];
	private SharedPreferences scores;
	private Sprite high;
	ServerScore server;
	TiledSprite topscore;
	RotationModifier rotateTopscore;
	ArrayList<Score> arr;

	@Override
	public void createScene() {
		server=new ServerScore();
		creatbackground();
		loadscore();
		//createButton();
		
		Sprite bar = new Sprite(0, -250,activity.CAMERA_WIDTH,130,resourcesManager.bar_region, vbom);
		bar.setAlpha(0.8f);
		bar.registerEntityModifier(new MoveYModifier(1, bar.getY(), 0));
		this.attachChild(bar);
		
		topscore = new TiledSprite(activity.CAMERA_WIDTH-150,activity.CAMERA_HEIGHT-140,130,130,resourcesManager.mTiledTextureRegionTopScoreWait, vbom);
		topscore.setCurrentTileIndex(0);
		rotateTopscore = new RotationModifier(3f, 0, 360);
		topscore.registerEntityModifier(new LoopEntityModifier(rotateTopscore));
		this.attachChild(topscore);
		this.setOnSceneTouchListener(this);
		
	}
	
	int i=0;
	public void loadscore()
	{
		arr = new ArrayList<Score>();
		arr = resourcesManager.getScoreFromSharedPreferences();
		final int centerX = (activity.CAMERA_WIDTH) / 2;   
		final int centerY = (activity.CAMERA_HEIGHT) / 2;
		mTitle = new Text( centerX + 100, centerY - 120, resourcesManager.font, "Score",vbom);
		//mTitle = new Text(pX, pY, pFont, pText, pVertexBufferObjectManager)
		attachChild(mTitle);
		mHeaders = new Text( centerX - 250, centerY - 120, resourcesManager.font, "Player",vbom);
		attachChild(mHeaders);
		/*final Timer loadscore=new Timer();

		loadscore.scheduleAtFixedRate(new TimerTask() {

			public void run() {
				int score = arr.get(i).score;
				String name = arr.get(i).player;
				Text t = new Text( centerX + 150, (centerY - 40) + (4-i)*40, resourcesManager.font, score+"",vbom);	
				attachChild(t);  
				t = new Text( centerX - 250, (centerY - 40) + (4-i)*40, resourcesManager.font, name,vbom);
				attachChild(t);
				createExplosion(centerX + 150, (centerY - 40) + (4-i)*40,t.getParent());
				i++;
				if(i==5)
					loadscore.cancel();
				Log.d("loadscoresf",loadscore+"");
			}
		}, 100, 500);*/
		
		float dur = 0.5f;

		for (i=0; i<5; i++){ 
			int score = arr.get(i).score;
			String name = arr.get(i).player;
			final Text t = new Text( centerX + 150, (centerY - 40) + (4-i)*40, resourcesManager.font, score+"",vbom);
			attachChild(t);  
			t.setVisible(false);
			final Text t2 = new Text( centerX - 250, (centerY - 40) + (4-i)*40, resourcesManager.font, name,vbom);
			attachChild(t2);
			t2.setVisible(false);
			final ScaleModifier mod1 = new ScaleModifier(0.7f, 0.1f, 1.3f);
			final ScaleModifier mod2 = new ScaleModifier(0.3f, 1.3f, 1f);
			createExplosion(centerX + 150, (centerY - 40) + (4-i)*40,t.getParent());
			TimerHandler timer = new TimerHandler(dur, false,new ITimerCallback() {
				
				@Override
				public void onTimePassed(TimerHandler pTimerHandler) {
					t.setVisible(true); 
					t2.setVisible(true);
					t.registerEntityModifier(new SequenceEntityModifier(mod1,mod2));
					t2.registerEntityModifier(new SequenceEntityModifier(mod1,mod2));
					
				}
			});
			engine.registerUpdateHandler(timer);
			dur += 0.3;
		}  
	}
	private void createExplosion(final float posX, final float posY,final IEntity target) {
		int mNumPart = 30;
		int mTimePart = 2;
		PointParticleEmitter particleEmitter = new PointParticleEmitter(posX,posY);
		IEntityFactory<Sprite> recFact = new IEntityFactory<Sprite>() {
			@Override
			public Sprite create(float pX, float pY) {
				Sprite rect = new Sprite(pX, pY, resourcesManager.star1_region, vbom);
				return rect;
			}

		};
		final ParticleSystem<Sprite> particleSystem = new ParticleSystem<Sprite>(recFact, particleEmitter, 10, 10, mNumPart);
		particleSystem.addParticleInitializer(new VelocityParticleInitializer<Sprite>(-50, 50, -50, 50));
		//particleSystem.addParticleModifier(new AlphaParticleModifier<Sprite>(0,0.6f * mTimePart, 1, 0));
		particleSystem.addParticleModifier(new RotationParticleModifier<Sprite>(0,mTimePart, 0, 360));
		//particleSystem.addParticleInitializer(new ExpireParticleInitializer<Sprite>(3.5f));
		
		particleSystem.addParticleModifier(new ScaleParticleModifier<Sprite>(0, 1f, 0.5f, 1.0f));
		particleSystem.addParticleModifier(new AlphaParticleModifier<Sprite>(1f, 1.5f, 1.0f, 0.0f));
		//particleSystem.addParticleModifier(new AlphaParticleModifier<Sprite>(3.5f, 4.5f, 0.0f, 1.0f));
		//particleSystem.addParticleModifier(new AlphaParticleModifier<Sprite>(4.5f, 11.5f, 1.0f, 0.0f));
		
		target.attachChild(particleSystem);
	}
	
	/*public void createButton()
	{
		MenuScene menuChildScene = new MenuScene(camera);
		menuChildScene.setPosition(0, 0);

		final IMenuItem playMenuItem = new ScaleMenuItemDecorator(
				new SpriteMenuItem(0,250,47, resourcesManager.btnscore_region,vbom), 1.2f, 1);
		menuChildScene.addMenuItem(playMenuItem);

		menuChildScene.buildAnimations();
		menuChildScene.setBackgroundEnabled(false);
		playMenuItem.setPosition(activity.CAMERA_WIDTH/2-playMenuItem.getWidth()/2, activity.CAMERA_HEIGHT-57);

		menuChildScene.setOnMenuItemClickListener(this);
		setChildScene(menuChildScene);
	}*/
	private void toast(final String pMessage) {
		new Runnable() {
			@Override
			public void run() {
				Toast.makeText(activity.getApplicationContext(), pMessage, Toast.LENGTH_SHORT).show();
			}
		};
	}
	/*@Override
	public boolean onMenuItemClicked(MenuScene pMenuScene, IMenuItem pMenuItem,
			float pMenuItemLocalX, float pMenuItemLocalY) {
		switch (pMenuItem.getID()) {
		case 0:
			server.showHighScore();
			return true;
		default:
			return false;
		}
	}*/

	
	public void creatbackground()
	{
		
		high = new Sprite(0, 0,activity.CAMERA_WIDTH,activity.CAMERA_HEIGHT, resourcesManager.backscore_region, vbom)
		{
		    @Override
		    protected void preDraw(GLState pGLState, Camera pCamera) 
		    {
		       super.preDraw(pGLState, pCamera);
		       pGLState.enableDither();
		    }
		};
		        
		//splash.setScale(1.5f);
		high.setPosition(0, 0);
		attachChild(high);
	}
	@Override
	public void onBackKeyPressed() {
		// TODO Auto-generated method stub
		SceneManager.getInstance().loadMenuScene(engine);
	}

	@Override
	public SceneType getSceneType() {
		// TODO Auto-generated method stub
		return SceneType.SCENE_HIGHSCORE;
	} 

	@Override
	public void disposeScene() {
		// TODO Auto-generated method stub
		
	}
	int x1Convert, y1Convert, x2Convert, y2Convert;
	public void convertTouch(int x1, int y1, int x2, int y2)
	{
		x1Convert = (int) (x1*resourcesManager.wRate);
		y1Convert = (int) (y1*resourcesManager.hRate);
		x2Convert = (int) (x2*resourcesManager.wRate);
		y2Convert = (int) (y2*resourcesManager.hRate);
		
		Log.d("inconvert", x1+"->"+x1Convert+":"+y1+"->"+y1Convert);
	}
	
	public void waiting()
	{
		rotateTopscore.reset(1f, 360, 0);
		topscore.setCurrentTileIndex(1);
	}
	public void unwaiting()
	{
		rotateTopscore.reset(3f, 0, 360);
		topscore.setCurrentTileIndex(0);

	}
	
	Point currPoint=new Point(); 
	Point prevPoint=new Point();
	Line line;

	@Override
	public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
		// TODO Auto-generated method stub
		synchronized (this) {
			switch (pSceneTouchEvent.getAction()) {
			case MotionEvent.ACTION_DOWN:
				currPoint=new Point();
				currPoint.x=(int) pSceneTouchEvent.getMotionEvent().getX();
				currPoint.y=(int) pSceneTouchEvent.getMotionEvent().getY();
				break;
			case MotionEvent.ACTION_UP:
				this.detachChild(line);
				break; 
			case MotionEvent.ACTION_MOVE:
				prevPoint=new Point();
				prevPoint.x = (int) pSceneTouchEvent.getMotionEvent().getX();
				prevPoint.y = (int) pSceneTouchEvent.getMotionEvent().getY();
				Log.d("prevPoint",prevPoint.x+":"+prevPoint.y);
				convertTouch(prevPoint.x, prevPoint.y,currPoint.x, currPoint.y);
				line = new Line(x2Convert,y2Convert,x1Convert,y1Convert,vbom);
				Log.d("x2Convert",x2Convert+":"+y2Convert+"-"+x1Convert+":"+y1Convert);
				line.setLineWidth(3);
				line.setAlpha(0);
				this.attachChild(line);
				//topscore.set
				if(topscore.collidesWith(line))
				{
					if(server.touch){
						resourcesManager.sliceSound.play();
						//touch=false;
						//touchcount++;
						server.showHighScore();
					}
				}
				currPoint = prevPoint;
				break;
			}
			return true;
		}
	}
}
